﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class UIAutoScroll : MonoBehaviour {

    public enum eAutoScrollDirection { horizontal,verticle}

    public bool IsEnabled { get; set; }

    public int cellHeight = 230;
    public int cellWidth = 230;
    public int offsetPerFrame = 2;
    public int limitChildCount = 4;
    public bool autoScrollOnAwake = true;
    public int childAlignSpace = 0;
    public eAutoScrollDirection autoScrollDirction;

    RectTransform _rt;
    int _total;
    int _activedChildCount;


    void Start()
    {
        _rt = GetComponent<RectTransform>();
        
        IsEnabled = autoScrollOnAwake;

        var allchilds = _rt.GetComponentsInChildren<UnityEngine.UI.Image>(true);
        _activedChildCount = allchilds.Length;

        for (var i = allchilds.Length - 1; i >= 0; i--)
        {
            var child = allchilds[i];

            if (child.gameObject.activeInHierarchy == false)
            {
                Destroy(child.gameObject);
                _activedChildCount -= 1;
            }
        }
    }

    void Update()
    {
        if (IsEnabled == false || _activedChildCount <= limitChildCount)
        {
            return;
        }

        switch (autoScrollDirction)
        {
            case eAutoScrollDirection.horizontal:
                ScrollHorizon();
                break;
            case eAutoScrollDirection.verticle:
                ScrollVerticle();
                break;
            default:
                break;
        }
    }

    private void ScrollVerticle()
    {
        _rt.anchoredPosition = new Vector2(0f, _rt.anchoredPosition.y + offsetPerFrame);
        _total += offsetPerFrame;

        if (_total % (cellHeight + childAlignSpace) == 0)
        {
            _rt.GetChild(0).SetAsLastSibling();
            _rt.anchoredPosition = Vector2.zero;
            _total = 0;
        }
    }

    private void ScrollHorizon()
    {
        _rt.anchoredPosition = new Vector2(_rt.anchoredPosition.x + offsetPerFrame,0f);
        _total += offsetPerFrame;

        if (_total % (cellWidth + childAlignSpace) == 0)
        {
            _rt.GetChild(0).SetAsLastSibling();
            _rt.anchoredPosition = Vector2.zero;
            _total = 0;
        }
    }
}
